package cn.j229.bug.zhongxuan.hualian.controller;

import cn.j229.bug.zhongxuan.hualian.exception.BusinessException;
import cn.j229.bug.zhongxuan.hualian.pojo.User;
import cn.j229.bug.zhongxuan.hualian.service.UserService;
import cn.j229.bug.zhongxuan.hualian.utils.JsonResult;
import cn.j229.bug.zhongxuan.hualian.utils.RandomCheckCode;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.rmi.ServerException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author smile_ZhongXuan
 * @Date 2020/10/21 10:06
 * @Version 1.0
 */
@RestController
@RequestMapping("/sms")
public class SMSController {

    @Resource
    UserService userService = null;
    @Resource
    RedisTemplate<String,Object> redisTemplate = null;
    JsonResult jsonResult = new JsonResult();

    @PostMapping("/send")
    public Map send(@RequestParam(value = "phone") String phone){
        // 判断该手机号是否是已注册的用户
        User findUserByPhone = userService.findUserByPhone(phone);
        // 如果是，则提示：该用户已经注册，请更换另一个手机号进行注册或直接登录
        if(findUserByPhone != null){
            // 前端收到0，和信息
            jsonResult.setCode("0");
            throw new BusinessException("该用户已经注册，请更换一个手机号进行注册或直接登录");
        }else{
            // 如果不是，可以注册，则调用阿里云短信接口，实现发送
            // 接收来自阿里云的返回数据
            // 根据返回值给用户提示
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                    "LTAI4FySuvcUsHdY3PPKtGf7", "iGeznddBMKjIqFmVkALHJcFTQhnSw6");
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", "国信安");
            request.putQueryParameter("TemplateCode", "SMS_204971035");

            String code = RandomCheckCode.getRandomCheckCodeNumberMethodOne();
//            String code = RandomCheckCode.getRandomCheckCode();
            // 给阿里云短信模板中的${code}赋值，json格式
            request.putQueryParameter("TemplateParam", "{'code':"+code+"}");
            try {
                CommonResponse response = client.getCommonResponse(request);
                // 获取的验证码数据,
                String data = response.getData();
                //{"Message":"OK","RequestId":"CBC83055-A113-483A-91B2-0E4C56CCC643","BizId":"790710603115763709^0","Code":"OK"}

                // 利用Jackson的ObjectMapper从json字符串中获取指定字段
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> tmpMap=mapper.readValue(data, Map.class);
                if("OK".equals(tmpMap.get("Code"))){
                    jsonResult.setCode("200");
                    jsonResult.setMsg("验证码发送成功");
                    // 将数据保存在redis服务器上, 15分钟有效
                    // 设置生存时间
                    ValueOperations<String, Object> operations = redisTemplate.opsForValue();
                    operations.set(phone,code,15, TimeUnit.DAYS);
                }else{
                    jsonResult.setCode("0");
                    jsonResult.setMsg("验证码发送失败,请检查手机号或稍后再试");
                }
            } catch (ClientException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return jsonResult.getValues();
    }
}
